package com.j2bugzilla.rpc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.j2bugzilla.base.BugHistoryDetail;
import com.j2bugzilla.base.BugHistoryFactory;
import com.j2bugzilla.base.BugzillaMethod;

public class BugHistory implements BugzillaMethod {

	private static final String BUG_HISTORY = "Bug.history";
	
	private Map<Object, Object> hash = new HashMap<Object, Object>();
	private Map<Object, Object> params = new HashMap<Object, Object>();

	public BugHistory(Integer id) {
		this(Collections.singletonList(id));
	}
	
	public BugHistory(List<Integer> ids) {
		params.put("ids", ids);
	}
	
	public List<BugHistoryDetail> getBugHistory() {
		List<BugHistoryDetail> result = new ArrayList<BugHistoryDetail>();
		if(hash.containsKey("bugs")) {
			
			Object[] bugs = (Object[])hash.get("bugs");
			if(bugs.length == 0) { 
				return result; //early return if map is empty
			}
			
			for(Object o : bugs) {
				@SuppressWarnings("unchecked")
				Map<String, Object> bugMap = (HashMap<String, Object>)o;
				result.add(new BugHistoryFactory().createBugHistory(bugMap));
			}
		}
		return result;
	}
	
	@Override
	public void setResultMap(Map<Object, Object> hash) {
		this.hash = hash;
	}

	@Override
	public Map<Object, Object> getParameterMap() {
		return Collections.unmodifiableMap(params);
	}

	@Override
	public String getMethodName() {
		return BUG_HISTORY;
	}
	
}
